﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CommonModule;
using System.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Oracle;
using DreamBuilder.Core.DAO;

namespace ePlanet.ArchiveMange.DataAccess
{
    public class ArchiveCommon : DataHelper
    {
        public ArchiveCommon()
        {
            if (!(this.DBHelper.database is OracleDatabase))
            {
                throw new Exception("只支持Oracle数据库");
            }
        }

        internal new bool SaveData(DataSet ds)
        {
            base.InsertData(ds);
            return true;
        }

        internal bool SaveAttach(DataTable dt_Attach, string objectTableName, string objectID, string DBHelperString)
        {
            this.DBHelper = DBHelperFactory.CreateInstance(DBHelperString);
            if (!(this.DBHelper.database is OracleDatabase))
            {
                throw new Exception("只支持Oracle数据库");
            }
            if (dt_Attach != null && dt_Attach.Rows.Count > 0)
            {
                foreach (DataRow arow in dt_Attach.Rows)
                {
                    if (int.Parse(arow["RowStatus"].ToString()) == 3) //状态为3则是删除该列
                    {
                        try
                        {
                            string sql = string.Format("Delete FROM P_BT_Attachments Where AttachmentID='{0}'", arow["AttachmentID"].ToString());
                            DBHelper.ExecuteSql(sql);
                        }
                        catch { return false; }
                    }
                    if (int.Parse(arow["RowStatus"].ToString()) == 2)//状态为2是修改该列
                    {
                        try
                        {
                            string sql = string.Format("Update P_BT_Attachments Set ObjectTableName='{0}',ObjectID='{1}' Where AttachmentID='{2}'", objectTableName, objectID, arow["AttachmentID"].ToString());
                            DBHelper.ExecuteSql(sql);
                        }
                        catch { return false; }
                    }
                }
            }
            return true;
        }

        internal DataSet GetAttach(string ObjectID, string DBHelperString)
        {
            this.DBHelper = DBHelperFactory.CreateInstance(DBHelperString);
            if (!(this.DBHelper.database is OracleDatabase))
            {
                throw new Exception("只支持Oracle数据库");
            }
            string sql = "select attachmentid,objecttablename,objectid,attachmentname,uploadtime,attachmentsize,documenttype,filetypeid,fileurl,createuserid,remark from P_BT_Attachments where ObjectID='" + ObjectID + "'";
            return this.DBHelper.ExecuteDataSet(sql);
        }

        internal byte[] GetAttachContentByID(string dataID, string DBHelperString)
        {
            byte[] rtnContent = null;
            this.DBHelper = DBHelperFactory.CreateInstance(DBHelperString);
            string sql = "select attachmentcontent from P_BT_Attachments where attachmentid='" + dataID + "'";
            object obj = this.DBHelper.ExecuteScalar(sql);
            if (obj != null)
            {
                rtnContent = (byte[])obj;
            }
            return rtnContent;
        }

        internal bool SavePageFile(IList<string> fileIdList, string ArchiveId)
        {
            StringBuilder keys = new StringBuilder("");
            foreach (string s in fileIdList)
            {
                keys.Append("'" + s + "',");
            }
            if (keys.Length > 0)
            {
                keys = keys.Remove(keys.Length - 1, 1);
            }
            string sql = string.Empty;
            if (ArchiveId != null)
            {
                sql = "update pagefile set f_ArchiveId='" + ArchiveId + "' where DATAID in (" + keys + ")";
            }
            else
            {
                sql = "update pagefile set f_ArchiveId = null where DATAID in (" + keys + ")";
            }
            int i = 0;
            if (keys.Length > 0)
            {
                i = this.DBHelper.ExecuteSql(sql);
            }
            else
            {
                return true;
            }
            return i > 0 ? true : false;
        }


        /// <summary>
        /// 根据档案ID获取卷内件
        /// </summary>
        /// <param name="DATAID"></param>
        /// <returns></returns>
        internal DataTable GetPageFileByDATAID(string DATAID)
        {
            string sql = "select * from pagefile t where t.f_ArchiveId='" + DATAID + "' ";
            return this.DBHelper.ExecuteDataSet(sql).Tables[0];
        }

        /// <summary>
        /// 获取某种类型档案的活动件
        /// </summary>
        /// <param name="archiveType"></param>
        /// <returns></returns>
        internal DataTable GetPageFileByArchiveType(string archiveType)
        {
            string sql = "select * from pagefile t where t.archivetype='" + archiveType + "' and t.f_ArchiveId is null";
            return this.DBHelper.ExecuteDataSet(sql).Tables[0];
        }

        public bool IsSameSecret(List<Guid> dataIDList)
        {
            return true;
        }

         public string GetArchiveDBTableName(string archiveTypeId)
        {
            switch (archiveTypeId)
            {
                case "1":
                    return "document_archive";
                case "2":
                    return "cd_archive";
                case "3":
                    return "technology_archive";
                case "4":
                    return "bulidproject_archive";
                case "5":
                    return "equipment_archive";
                case "6":
                case "61":
                case "62":
                case "63":
                case "64":
                    return "account_voucher_archive";
                case "7":
                case "71":
                case "72":
                    return "olisearch_archive";
                case "8":
                case "81":
                case "82":
                case "83":
                    return "audiovedio_archive";
                case "9":
                case "91":
                case "92":
                case "93":
                case "94":
                    return "realkind_archive";
                case "101":
                    return "DOCUMENT_ARCHIVE_VOL";
                case "102":
                    return "DOCUMENT_ARCHIVE_VOL_File";
                case "7101":
                    return "OLISEARCH_ZongHe_VOL";
                case "7102":
                    return "OLISEARCH_ZongHe_VOL_FILE";
                default:
                    throw new Exception("there is no database table for this archive with ArchiveTypeId = " + archiveTypeId);
            }
        }

        public DataTable GetArchiveByPage(int finishStatusId, string archiveTypeId, int beginNum, int count, out int sum, string where)
        {
            string archiveTableName = GetArchiveDBTableName(archiveTypeId);



            int total = 0;
            string getSumSql = string.Format("select count(*) from {0} where archiveType='{1}' and statusid={2} and {3}", archiveTableName, archiveTypeId, finishStatusId, where);
            //string queryDatasql = string.Format(" select * from {0} where archiveType='{1}' rownum between {2} and {3} ", archiveTableName, archiveTypeId, beginNum, beginNum + count);
            string queryDatasql = string.Format("select * from (select A.*, rownum NumberIndex from (select * from {0} where archivetype = {1} and statusid={4} and {5} order by archivenum) A where rownum < {2}) b where NumberIndex >= {3}",
                                                archiveTableName, archiveTypeId, beginNum + count, beginNum, finishStatusId, where);

            DataTable oDataTable = new DataTable();
            if (this.DBHelper.database is OracleDatabase)
            {
                total = int.Parse(DBHelper.ExecuteScalar(getSumSql).ToString());
                DataSet ds = this.DBHelper.ExecuteDataSet(queryDatasql);
                if (ds != null && ds.Tables.Count > 0)
                {
                    oDataTable.Merge(ds.Tables[0]);
                }
                sum = total;
                return oDataTable;
            }
            else
            {
                throw new Exception("只支持Oracle数据库");
            }
        }

        public DataTable GetArchiveByIds(IList<string> idList, int archiveTypeId)
        {
            try
            {
                StringBuilder keys = new StringBuilder("");
                foreach (string s in idList)
                {
                    keys.Append("'" + s + "',");
                }
                if (keys.Length > 0)
                {
                    keys = keys.Remove(keys.Length - 1, 1);
                }
                string archiveTableName = GetArchiveDBTableName(archiveTypeId.ToString());
                string sql = "select * from  " + archiveTableName + "  where archivetype = " + archiveTypeId + " and DataId in (" + keys + ")";
                DataSet ds = this.DBHelper.ExecuteDataSet(sql);
                return ds.Tables[0];
            }
            catch
            {
                throw;
            }
        }

        public void DeleteArchive(string id, int archiveTypeId)
        {
            try
            {
                string archiveTableName = GetArchiveDBTableName(archiveTypeId.ToString());
                string sql = string.Format("delete from {0} where DataId = '{1}' and archivetype = {2}", archiveTableName, id, archiveTypeId);
                this.DBHelper.ExecuteSql(sql);
            }
            catch
            {
                throw;
            }
        }

        public DataTable GetArchiveByArchiveNums(IList<string> archiveNums, string archiveTypeId)
        {
            try
            {
                StringBuilder keys = new StringBuilder("");
                foreach (string s in archiveNums)
                {
                    keys.Append("'" + s + "',");
                }
                if (keys.Length > 0)
                {
                    keys = keys.Remove(keys.Length - 1, 1);
                }
                string archiveTableName = GetArchiveDBTableName(archiveTypeId);
                string sql = "select * from  " + archiveTableName + "  where archivetype = " + archiveTypeId + " and archivenum is not null and archivenum in (" + keys + ")";
                DataSet ds = this.DBHelper.ExecuteDataSet(sql);
                return ds.Tables[0];
            }
            catch
            {
                throw;
            }
        }

        /// <summary>
        /// 根据表名和ID更新特定档案的全宗号
        /// </summary>
        /// <param name="fullfondsnum">全宗号</param>
        /// <param name="tablename">档案表名</param>
        /// <param name="archiveid">档案ID</param>
        /// <returns></returns>
        public bool UpdateFullFondsNum(string fullfondsnum,string tablename,string archiveid)
        {
            string sqlformat = "update {0} set FULLFONDSNUM ='{1}' where dataid='{2}'";
            string sql = string.Format(sqlformat, tablename, fullfondsnum, archiveid);
            int i = DBHelper.ExecuteSql(sql);
            return i > 0 ? true : false;
        }
    }
}
